import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Card, Slider, InputNumber, Row, Col, Typography, ConfigProvider, theme } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { useSegmentForm, useDebouncedSave } from './hooks';

const { Text } = Typography;

export interface AudioSettings {
    volume: number; // 音量大小，0-100
}

interface AudioSettingsProps {
    disabled?: boolean;
    // 用于从 Redux 获取片段数据
    trackId?: string;
    segmentId?: string;
    // 用于防抖保存的参数
    draftId?: string;
}

const AudioSettingsComponent: React.FC<AudioSettingsProps> = ({ disabled = false, trackId, segmentId, draftId }) => {
    // 使用新的 store hook
    const { setCurrentSegmentInfo, updateSegmentConfig } = useSegmentForm();
    const debouncedSave = useDebouncedSave(800);

    // 防抖定时器引用
    const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 从 Redux 获取基础数据
    const scriptData = useSelector((state: RootState) => state.drafts.scriptData);

    // 使用 useMemo 优化片段数据获取
    const segment = useMemo(() => {
        if (!trackId || !segmentId || !scriptData?.tracks) return null;

        const track = scriptData.tracks.find((track: any) => track.id === trackId);
        if (!track || !track.segments) return null;

        return track.segments.find((segment: any) => segment.id === segmentId) || null;
    }, [trackId, segmentId, scriptData?.tracks]);

    // 使用 useMemo 优化轨道数据获取
    const currentTrack = useMemo(() => {
        if (!scriptData?.tracks) return null;
        return scriptData.tracks.find((track: any) => track.id === trackId) || null;
    }, [trackId, scriptData?.tracks]);

    // 默认的音频设置
    const defaultSettings: AudioSettings = {
        volume: 100,
    };

    // 从片段数据中获取音量设置，如果没有则使用默认值
    const getInitialSettings = () => {
        if (segment?.volume !== undefined) {
            return { volume: Math.round(segment.volume * 100) };
        }
        return defaultSettings;
    };

    const [currentSettings, setCurrentSettings] = useState<AudioSettings>(getInitialSettings());

    // 设置当前片段信息到 store
    useEffect(() => {
        if (trackId && segmentId && draftId && segment) {
            setCurrentSegmentInfo({
                draftId,
                trackId,
                segmentId,
                type: currentTrack?.type as any,
                materialId: segment.material_id,
                start: segment.target_timerange?.start || 0,
                duration: segment.target_timerange?.duration || 0,
            });
        }
    }, [trackId, segmentId, draftId, segment, currentTrack, setCurrentSegmentInfo]);

    // 当片段数据变化时，更新内部状态
    useEffect(() => {
        if (segment?.volume !== undefined) {
            setCurrentSettings({ volume: Math.round(segment.volume * 100) });
        }
    }, [segment?.volume]);

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);

    // 防抖更新设置 - 用于连续调整的操作（如滑块拖拽）
    // 策略：立即更新UI状态，延迟300ms后更新store和保存
    const debouncedUpdateSettings = useCallback(
        (newSettings: AudioSettings) => {
            // 清除之前的定时器
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }

            // 立即更新本地状态（用于UI响应）
            setCurrentSettings(newSettings);

            // 设置防抖定时器
            debounceTimerRef.current = setTimeout(() => {
                // 更新到 store (volume 需要转换为 0-1 范围)
                updateSegmentConfig({ volume: newSettings.volume / 100 });
                // 触发防抖保存
                debouncedSave({ volume: newSettings.volume / 100 });
            }, 300); // 300ms 防抖延迟
        },
        [updateSegmentConfig, debouncedSave]
    );

    // 立即更新设置 - 用于离散操作（如输入框直接输入）
    // 策略：立即更新UI状态、store和保存
    const immediateUpdateSettings = useCallback(
        (newSettings: AudioSettings) => {
            setCurrentSettings(newSettings);
            updateSegmentConfig({ volume: newSettings.volume / 100 });
            debouncedSave({ volume: newSettings.volume / 100 });
        },
        [updateSegmentConfig, debouncedSave]
    );

    // 处理音量变化（防抖）
    const handleVolumeChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({
                ...currentSettings,
                volume: value,
            });
        },
        [currentSettings, debouncedUpdateSettings]
    );

    // 处理输入框音量变化（立即更新）
    const handleInputVolumeChange = useCallback(
        (value: number) => {
            immediateUpdateSettings({
                ...currentSettings,
                volume: value,
            });
        },
        [currentSettings, immediateUpdateSettings]
    );

    const darkTheme = {
        algorithm: theme.darkAlgorithm,
        token: {
            colorPrimary: '#715bb8',
            colorBgContainer: '#2a2a2a',
            colorBgElevated: '#2a2a2a',
            colorText: '#ffffff',
            colorTextSecondary: 'rgba(255, 255, 255, 0.7)',
            colorBorder: '#434343',
            colorBorderSecondary: '#434343',
            borderRadius: 6,
            colorFillSecondary: '#434343',
        },
        components: {
            Card: {
                colorBgContainer: '#2a2a2a',
                colorBorderSecondary: '#434343',
            },
            Slider: {
                colorBgContainer: '#2a2a2a',
                colorPrimary: '#715bb8',
                colorPrimaryBorder: '#715bb8',
                colorFillSecondary: '#434343',
                colorText: '#ffffff',
            },
            InputNumber: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
                colorText: '#ffffff',
                colorTextPlaceholder: 'rgba(255, 255, 255, 0.3)',
            },
        },
    };

    return (
        <ConfigProvider theme={darkTheme}>
            <Card
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <AudioOutlined style={{ color: '#715bb8' }} />
                        <span style={{ color: '#ffffff' }}>音频设置</span>
                    </div>
                }
                style={{
                    backgroundColor: '#2a2a2a',
                    border: '1px solid #434343',
                    borderRadius: '8px',
                }}
                styles={{ body: { padding: '12px' } }}
            >
                <div style={{ marginBottom: '12px' }}>
                    <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>音量大小</Text>
                    <Row align="middle" gutter={12}>
                        <Col span={18}>
                            <Slider min={0} max={100} value={currentSettings.volume} onChange={handleVolumeChange} disabled={disabled} style={{ margin: '0' }} />
                        </Col>
                        <Col span={6}>
                            <InputNumber
                                min={0}
                                max={100}
                                value={currentSettings.volume}
                                onChange={(value) => (typeof value === 'number' ? handleInputVolumeChange(value) : handleInputVolumeChange(0))}
                                disabled={disabled}
                                style={{ width: '100%' }}
                                size="small"
                                suffix="%"
                            />
                        </Col>
                    </Row>
                </div>
            </Card>
        </ConfigProvider>
    );
};

export default AudioSettingsComponent;
